wx.cloud.init()
const db = wx.cloud.database()
const orderCollection = db.collection('subscribe')
const _ = db.command
Component({
  data: {
    showTopTips: false,
    formData: {
    },
    rules: [{
      name: 'class',
      rules: { required: true, message: '辅导科目是必选项' },
    }, {
        name: 'grade',
        rules: { required: true, message: '辅导年级是必选项' },
      }, {
        name: 'contactname',
        rules: { required: true, message: '联系人姓名是必选项' },
      }, {
        name: 'telphone',
        rules: [{ required: true, message: '手机号必填' }, { mobile: true, message: '手机号格式不对' }],
      }, {
        name: 'microno',
        rules: { required: true, message: '微信号是必选项' },
      }]
  },
  methods: {
    formInputChange(e) {
      const { field } = e.currentTarget.dataset
      this.setData({
        [`formData.${field}`]: e.detail.value
      })
    },
    submitForm() {
      this.selectComponent('#form').validate((valid, errors) => {
        console.log('valid', valid, errors)
        if (!valid) {
          const firstError = Object.keys(errors)
          if (firstError.length) {
            this.setData({
              error: errors[firstError[0]].message
            })

          }
        } else {
          console.log(this.data.formData)
          var address ="";
          var demand = ""; 
            if(this.data.formData.hasOwnProperty('address')){
            address = this.data.formData.address;
            console.log(address)
          }
          if (this.data.formData.hasOwnProperty('demand')){
            demand = this.data.formData.demand;
          }
          orderCollection.add({
            // data 字段表示需新增的 JSON 数据
            data:{
              class:this.data.formData.class,
              grade:this.data.formData.grade,
              contactname:this.data.formData.contactname,
              telphone:this.data.formData.telphone,
              microno:this.data.formData.microno,
              address:address,
              demand:demand,
              createtime: new Date(),
              status:0
            }
          })
            .then(res => {
              console.log(res)
              wx.showToast({
                title: '预约成功',
                icon: 'success',
                duration: 2000
              })
              wx.switchTab({
                url: '../my/my',
              })
            })
            .catch(console.error)
        }
      })
    }

  }
});